import mongoose, { Connection } from "mongoose";

export const createDb = (dbName = "", tableName = "") => {
  const db: Connection = mongoose.createConnection(
    `${process.env.MONGO_URL}/${dbName}`,
    {}
  );

  db.on("open", () => {
    console.log(
      `${tableName ? tableName + " 数据表 " : ""}连接 ${dbName} 数据库成功`
    );
  });

  // 当连接发生错误时触发
  db.on("error", (err) => {
    console.error(
      `${tableName ? tableName + " 数据表 " : ""}连接 ${dbName} 数据库出错:`,
      err
    );
  });

  // 当连接断开时触发
  db.on("disconnected", () => {
    console.log(
      `${tableName ? tableName + " 数据表 " : ""}断开 ${dbName} 数据库`
    );
  });

  // 当连接正在建立时触发
  db.on("connecting", () => {
    console.log(
      `${tableName ? tableName + " 数据表 " : ""}正在连接 ${dbName} 数据库...`
    );
  });

  // 当连接正在断开时触发
  db.on("disconnecting", () => {
    console.log(
      `${tableName ? tableName + " 数据表 " : ""}正在断开 ${dbName} 数据库...`
    );
  });

  // 当重新建立连接时触发
  db.on("reconnected", () => {
    console.log(
      `${tableName ? tableName + " 数据表 " : ""}重新连接 ${dbName} 数据库成功`
    );
  });

  // 关闭连接时触发
  db.on("close", () => {
    console.log(
      `${tableName ? tableName + " 数据表 " : ""}关闭 ${dbName} 数据库成功`
    );
  });

  return db;
};
